﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using FZ.Common;
using TongJi.Bll;
using TongJi.Model;

namespace TongJi.Web
{
    /// <summary>
    /// TongJi 的摘要说明
    /// </summary>
    public class TongJi : IHttpHandler
    {
        private const string TongJiScriptContentCacheKey = "TongJi.Web.TongJi";
        private static DateTime TongJiScriptContentCacheTime = DateTime.MinValue;
        //  public static readonly string ServerHttpAddress = WebConfigHelper.GetAppSettings("ServerHttp");

        public void ProcessRequest(HttpContext context)
        {
            if (IsResponse304Cache(context))
            {
                return;
            }

            var Request = context.Request;
            var siteId = Request.QueryString["siteid"].ToInt();
            string responseContent;
            if (siteId > 0)
            {
                string msg;
                var checkStatus = new TongJiManager().CheckSiteStatus(context, out msg);
                if (checkStatus == CheckSiteStatusEnum.Error)
                {
                    responseContent = "alert('{0}')".FormatWith(msg);
                }
                else if (checkStatus == CheckSiteStatusEnum.Tip)
                {
                    responseContent = "/*{0}*/".FormatWith(msg);
                }
                else
                {
                    var dict = new Dictionary<string, string>
            {
                {"UserName", Request.QueryString["UserName"].HtmlEncode()},//用户名
                {"SiteId", siteId.ToString()},//站点编号
                {"UserRole", Request.QueryString["UserRole"].HtmlEncode()},//用户角色
                {"ManuallyLog", Request.QueryString["ManuallyLog"]=="1"?"1":null},//手动调用记录
                {"ServerPath", (Request.QueryString["ServerPath"]??"/").HtmlEncode()},//相对站点的虚拟目录【影响cookie的path】
               // {"Server", "{0}/log.ashx".FormatWith(ServerHttpAddress)}
            };
                    responseContent = GetTongJiScriptContent;
                    foreach (var item in dict)
                    {
                        responseContent = responseContent.Replace("{{" + item.Key + "}}", HttpUtility.HtmlEncode(item.Value));
                    }

                    ResponseCache(context);
                }
            }
            else
            {
                responseContent = "alert('统计代码缺少SiteId参数！')";
            }
            context.Response.ContentType = "text/javascript";
            context.Response.Write(responseContent);
        }

        public string GetTongJiScriptContent
        {
            get
            {
                var content = CacheHelper.GetCache(TongJiScriptContentCacheKey);
                if (content == null)
                {
                    var scriptPath = "~/tongji.js".ToMapPath();
                    content = File.ReadAllText(scriptPath);
                    TongJiScriptContentCacheTime = DateTime.Now;
                    CacheHelper.SetCache(TongJiScriptContentCacheKey, content, scriptPath);
                }
                return content.ToString();
            }
        }
        /// <summary>
        /// 判断客户端内容是否是当前最新缓存内容
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private bool IsResponse304Cache(HttpContext context)
        {
            var entity = context.Request.Headers["If-None-Match"];
            //304缓存
            if (entity != null && entity == TongJiScriptContentCacheTime.ToString())
            {
                context.Response.StatusCode = 304;
                ResponseCache(context);
                return true;
            }
            return false;
        }
        /// <summary>
        /// 将脚本写入浏览器缓存（默认在客户端缓存10分钟，之后才会重新请求）
        /// </summary>
        /// <param name="context"></param>
        private void ResponseCache(HttpContext context)
        {
            var Response = context.Response;
            Response.Cache.SetCacheability(HttpCacheability.Public);
            //将缓存时间点写入
            Response.Cache.SetETag(TongJiScriptContentCacheTime.ToString());
            //客户端缓存10分钟
            Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(10d));
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}